﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary
{
    /// <summary>
    ///  This class represents a Lagrange polynomial.
    /// </summary>
    [Serializable]
    public class LagrangePolynomial : AbstractRealPolynomial, ILagrangePolynomial
    {
        /// <summary>
        /// The x values of the polynomial.
        /// </summary>
        private readonly double[] xValues;

        /// <summary>
        /// The y values of the polynomial.
        /// </summary>
        private readonly double[] yValues;

        /// <summary>
        /// Initializes a new instance of the <see cref="LagrangePolynomial"/> class.
        /// </summary>
        /// <param name="xValues">The x values of the polynomial.</param>
        /// <param name="yValues">The y values of the polynomial.</param>
        public LagrangePolynomial(double[] xValues, double[] yValues)
        {
            if (xValues == (double[]) ((object) null))
            {
                throw new ArgumentNullException("xValues");
            }

            if (yValues == (double[]) ((object) null))
            {
                throw new ArgumentNullException("yValues");
            }

            if (xValues.Length != yValues.Length)
            {
                throw new Exception("The number of x values has to be even with the number of y values.");
            }

            if (xValues.Length < 2)
            {
                throw new ArgumentException("For an interpolation a minimum of two points are required.");
            }

            this.xValues = (double[]) xValues.Clone();
            this.yValues = (double[]) yValues.Clone();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LagrangePolynomial"/> class.
        /// </summary>
        /// <param name="polynomial">The polynomial to clone.</param>
        public LagrangePolynomial(LagrangePolynomial polynomial)
        {
            if (polynomial == (LagrangePolynomial) null)
            {
                throw new ArgumentNullException("polynomial");
            }

            this.xValues = (double[]) polynomial.XValues.Clone();
            this.yValues = (double[]) polynomial.YValues.Clone();
        }

        /// <summary>
        /// Gets the x values of the polynomial.
        /// </summary>
        /// <value>The x values of the polynomial.</value>
        public double[] XValues
        {
            get { return xValues; }
        }

        /// <summary>
        /// Gets the y values of the polynomial.
        /// </summary>
        /// <value>The y values of the polynomial.</value>
        public double[] YValues
        {
            get { return yValues; }
        }

        /// <summary>
        /// Compares the current instance to the specified polynomial.
        /// </summary>
        /// <param name="compare">The polynomial to compare.</param>
        /// <returns>True if both polynomials are even otherwise, false.</returns>
        public bool CompareTo(LagrangePolynomial compare)
        {
            return (this == compare);
        }

        /// <summary>
        /// Solves the polynomial at the specified position x.
        /// </summary>
        /// <param name="x">The value for evaluation.</param>
        /// <returns>The result f(x) at the specified position x.</returns>
        public override double SolveAt(double x)
        {
            double result = 0;

            for (int i = 0; i < this.xValues.Length; ++i)
            {
                double tempuri = 1;

                for (int j = 0; j < this.xValues.Length; ++j)
                {
                    if (j != i)
                    {
                        tempuri *= (x - this.xValues[j]) / (this.xValues[i] - this.xValues[j]);
                    }
                }

                result += tempuri * this.yValues[i];
            }

            return result;
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="a">The first LagrangePolynomial.</param>
        /// <param name="b">The second LagrangePolynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(LagrangePolynomial a, LagrangePolynomial b)
        {
            if (System.Object.ReferenceEquals(a, b))
            {
                return true;
            }

            if (((object) a == null) || ((object) b == null))
            {
                return false;
            }

            if (a.XValues.Length != b.XValues.Length)
            {
                return false;
            }

            if (a.YValues.Length != b.YValues.Length)
            {
                return false;
            }

            for (int i = 0; i < a.XValues.Length; i++)
            {
                if ((a.XValues[i] != b.XValues[i]) || (a.YValues[i] != b.YValues[i]))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="a">The first LagrangePolynomial.</param>
        /// <param name="b">The second LagrangePolynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(LagrangePolynomial a, LagrangePolynomial b)
        {
            return !(a == b);
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Converts the Lagrange polynomial to a normal polynomial.
        /// </summary>
        /// <returns>The converted polynomial.</returns>
        public SimplePolynomial ToPolynomial()
        {
            List<SimplePolynomial> workingPolynomials = new List<SimplePolynomial>();

            for (int i = 0; i < this.xValues.Length; ++i)
            {
                List<SimplePolynomial> factors = new List<SimplePolynomial>();

                for (int j = 0; j < this.xValues.Length; ++j)
                {
                    if (j != i)
                    {
                        SimplePolynomial tempuri = new SimplePolynomial(-this.xValues[j], 1);

                        tempuri.MultiplyWithScalar(1 / (this.xValues[i] - this.xValues[j]));
                        factors.Add(tempuri);
                    }
                }

                SimplePolynomial multiply = factors[0];

                for (int j = 1; j < factors.Count; j++)
                {
                    multiply *= factors[j];
                }

                multiply.MultiplyWithScalar(this.yValues[i]);

                workingPolynomials.Add(multiply);
            }

            SimplePolynomial result = workingPolynomials[0];

            for (int i = 1; i < workingPolynomials.Count; i++)
            {
                result += workingPolynomials[i];
            }

            return result;
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            String result = "";

            for (int i = 0; i < this.xValues.Length; ++i)
            {
                result += " + " + this.yValues[i].ToString();

                for (int j = 0; j < this.xValues.Length; ++j)
                {
                    if (j != i)
                    {
                        result += "((x - " + this.xValues[j].ToString() + ") / " + "(" +
                                  this.xValues[i].ToString() + " - " + this.xValues[j].ToString() + "))";
                    }
                }
            }

            if (result.Length > 3)
            {
                result = result.Substring(3);
            }

            return result;
        }
    }
}